import { ref } from 'vue';
import { defineStore } from 'pinia';
import { getToken } from '@/utils/storage';
import { ElMessage } from 'element-plus';

export const useWebsocketStore = defineStore('websocket', () => {
  const websocket = ref<WebSocket | null>(null);
  function connect() {
    if (websocket.value) {
      return websocket.value;
    }
    // token的获取要放到这里，如果放到函数外面，则当用户未登录时，获取到的值为undefined
    const token = getToken();
    const url = `wss://ly.guilinsx.com:9090/OnlineVideo/ws?token=${token}`;
    try {
      websocket.value = new WebSocket(url);
    } catch (error) {
      ElMessage.error({
        message: '连接服务器失败，请刷新页面后重试',
        duration: 2000,
      });
    }
    return websocket.value!;
  }
  function close() {
    if (websocket.value) {
      websocket.value.close(1000);
      websocket.value = null;
    }
  }
  // 使用该方法可以先对websocket的连接状态进行判断
  function sendMessage(message: string) {
    if (websocket.value?.readyState === WebSocket.CLOSED) {
      ElMessage({
        message: '连接已断开，请刷新页面或重新登录！',
        type: 'error',
      });
      return;
    }
    websocket.value?.send(message);
  }

  return { websocket, connect, close, sendMessage };
});
